package com.han.yweb.core;

import com.han.yweb.annotation.Bean;
import com.han.yweb.annotation.Starter;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class YwebServer implements Server {

    private final Map<String, String> map = new HashMap<>();

    @Override
    public void start(Class<?> clazz) throws ClassNotFoundException {
        Starter starter = clazz.getAnnotation(Starter.class);
        if (starter == null) {
            throw new IllegalArgumentException("启动类必须使用 @Starter 注解");
        }
        String packageName = clazz.getPackageName();
        URL url = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
        if (url != null) {
            String path = url.getPath();
            resolverPath(packageName, new File(path));
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                System.out.println(key + ": " + map.get(key));
            }
        }
    }

    private void resolverPath(String packageName, File file) throws ClassNotFoundException {
        if (file.isDirectory()) {
            findClassOnBean(packageName, file);
        } else {
            String path = file.getPath().replace(File.separator, ".");
            if (file.getName().endsWith(".class")) {
                String location = path.substring(path.indexOf(packageName)).replace(".class", "");
                Class<?> forName = Class.forName(location);
                Bean beanAnnotation = forName.getAnnotation(Bean.class);
                if (beanAnnotation != null) {
                    map.put(file.getName().replace(".class", ""), location);

                }
            }
        }
    }

    private void findClassOnBean(String packageName, File file) throws ClassNotFoundException {
        File[] files = file.listFiles();
        if (files == null || files.length <= 0) {
            return;
        }
        for (File child : files) {
            resolverPath(packageName, child);
        }
    }
}
